package main

import (
	"fmt"
	"sync"
)


// 使用channel 来等待 goroutine 结束 以及WaitGroup的使用

type worker struct {
	in   chan int
	done func()
}

func doWorker(i int, w worker) {
	//for {  //方式一
	//	n, ok := <-c
	//	if !ok {
	//		break
	//	}
	//	fmt.Printf("Worker %d received %d\n", i, n)
	//}

	for n := range w.in { //方式二
		fmt.Printf("Worker %d received %c\n", i, n)
		w.done()
	}
}

func createWorker(i int, wg *sync.WaitGroup) worker {
	w := worker{
		in:   make(chan int),
		done: func() {
			wg.Done()
		},
	}
	go doWorker(i, w)

	return w
}

func chanDemo1() {
	var wg sync.WaitGroup //使用系统提供的操作

	var workers [10]worker
	for i := 0; i < 10; i++ {
		workers[i] = createWorker(i, &wg)
	}
	wg.Add(20)
	for i, worker := range workers {
		worker.in <- 'a' + i
	}
	//for _, worker := range workers {
	//	<-worker.done //所有的channel发送都是阻塞的
	//}
	for i, worker := range workers {
		worker.in <- 'A' + i
	}
	//// wait for all of them
	//for _, worker := range workers {
	//	<-worker.done
	//}
	//等待所有的携程操作完成
	wg.Wait()
}

func main() {
	chanDemo1()
}
